import { useAppStore, useProfileStore, useAccountStore } from '@/store'

const APP_ID = import.meta.env.VITE_CS_APPID
// const APP_ID = 'ftfzy284' //production
const API_BASE = `https://${APP_ID}.intercom-messenger.com`
interface ParamsInfo {
	mobile?: string | null
	Userid?: number | null
	Username?: string | null
	Currency?: string | null
	Affiliateid?: number | null
	location?: string | null
}

function getParams() {
	const appStore = useAppStore()
	const profileStore = useProfileStore()
	const accountStore = useAccountStore()
	const params: ParamsInfo = {}
	if (accountStore.isLogin) {
		params.mobile = profileStore.userInfo?.mobile
		params.Userid = profileStore.userInfo?.userId
		params.Username = profileStore.userInfo?.userName
		params.Currency = profileStore.userInfo?.currency
		params.Affiliateid = profileStore.userInfo?.agentId
	}
	params.location = appStore.lang === 'zh' ? 'zh-CN' : appStore.lang
	return params
}

function getUpdateParams(params: ParamsInfo) {
	if (!params.Username) {
		console.log('new chat without login!!!')
		return {
			app_id: APP_ID,
			name: '',
			language_override: params.location,
			currency: '',
			user_id: '',
			affiliate_id: '',
			user_hash: '',
			api_base: API_BASE
		}
	} else {
		console.log('new chat with username !!!')
		return {
			app_id: APP_ID,
			name: params.Username,
			language_override: params.location,
			currency: params.Currency,
			user_id: params.Userid,
			affiliate_id: params.Affiliateid,
			user_hash: params.Userid,
			api_base: API_BASE
		}
	}
}

export function updateCS(falg: boolean) {
	const w = window as any
	const ic = w.Intercom
	if (typeof ic === 'function') {
		const updateParams = getUpdateParams(getParams())
		console.log(updateParams)
		if (
			updateParams.user_id !== w.intercomSettings?.user_id &&
			(updateParams.user_id || w.intercomSettings?.user_id)
		) {
			ic('reattach_activator')
			w.intercomSettings = updateParams
			ic('update', updateParams)
		}
		if (!falg) {
			ic('show')
		}
	} else {
		initCS()
	}
}

export function initCS() {
	const list = getParams()
	const csW = window as any
	const lang = list.location === 'zh' ? 'zh-CN' : list.location
	if (!list.Username) {
		console.log('new chat without login!!!')
		csW.intercomSettings = {
			app_id: APP_ID,
			language_override: lang,
			api_base: API_BASE
		}
	} else {
		console.log('new chat with username !!!')
		csW.intercomSettings = {
			app_id: APP_ID,
			name: list.Username,
			language_override: lang,
			currency: list.Currency,
			user_id: list.Userid,
			affiliate_id: list.Affiliateid,
			user_hash: list.Userid,
			api_base: API_BASE
		}
	}
	const w = window as any
	const ic = w.Intercom
	if (typeof ic === 'function') {
		ic('reattach_activator')
		ic('update', w.intercomSettings)
		// ic('show')
	} else {
		const i = function () {
			// eslint-disable-next-line prefer-rest-params
			i.c(arguments)
		}
		i.q = [] as Array<any>
		i.c = function (args: any) {
			i.q.push(args)
		}
		w.Intercom = i
		const l = function () {
			const s = document.createElement('script')
			s.type = 'text/javascript'
			s.async = true
			s.src = 'https://widget.intercom.io/widget/' + APP_ID
			const x = document.getElementsByTagName('script')[0]
			x.parentNode?.insertBefore(s, x)
		}
		if (document.readyState === 'complete') {
			l()
		} else if (w.attachEvent) {
			w.attachEvent('onload', l)
		} else {
			w.addEventListener('load', l, false)
		}
		// const csW = window as any
		// csW.Intercom('show')
	}
	// csW.Intercom('onHide', function () {
	// 	initializeIntercom()
	// })
	csW.Intercom('onShow', function () {
		updateCS(true)
	})
	// csW.Intercom('update', {
	// 	app_id: APP_ID,
	// 	language_override: lang
	// })

	//Clear relevant cookies or local storage
	// function clearIntercomState() {
	// 	console.log('clear clearIntercomState')
	// 	const cookieName = `intercom-session - ${APP_ID}`
	// 	document.cookie = cookieName + '= expires=Thu, 01 Jan 1970 00:00:00 UTC path=/'
	// }

	//Reinitialize Intercom while cleaning
	// function initializeIntercom() {
	// 	console.log('initializeIntercom')
	// 	clearIntercomState()
	// 	csW.Intercom('boot', {
	// 		app_id: APP_ID,
	// 		language_override: lang
	// 	})
	// }
}

export function updateCSLocation(val: boolean) {
	if (val) {
		document.body.setAttribute('openslidebar', 'true')
	} else {
		document.body.setAttribute('openslidebar', '')
	}
}
